#include "statusbarmanager.h"
#include "mainwindow.h"
#include "streamingexportmanager.h"
#include "statusbarinfo.h"
#include "versionmanager.h"
#include "pathmanager.h"

#include <QApplication>
#include <QDesktopServices>
#include <QUrl>
#include <QDebug>
#include <QStandardPaths>
#include <QProcess>
#include <QPainter>
#include <QPainterPath>
#include <QThread>
#include <QFile>
#include <QTextStream>
#include <QRegularExpression>

#ifdef Q_OS_MACOS
#include <sys/sysctl.h>
#include <sys/types.h>
#endif

#ifdef Q_OS_WIN
#include <windows.h>
#endif

StatusBarManager::StatusBarManager(MainWindow* mainWindow, QStatusBar* statusBar, QObject* parent)
    : QObject(parent)
    , m_mainWindow(mainWindow)
    , m_statusBar(statusBar)
    , m_streamingExportManager(nullptr)
    , m_compactMode(false)
    // , nullptr(new ExportStateManager(this))  // 移除：使用MergedExportManager的GlobalExportState统一状态管理
    , m_folderBlinkTimer(nullptr)
    , m_folderBlinkCount(0)
    , m_versionWidget(nullptr)    // 初始化版本控件为空
    , m_versionLabel(nullptr)    // 初始化版本标签为空
    , m_updateIconButton(nullptr) // 初始化更新图标按钮为空
    , m_currentGlobalPageLabel(nullptr) // 初始化全局页码标签为空
    , m_totalPagesLabel(nullptr)      // 初始化总页数标签为空
    , m_statusIndicatorButton(nullptr) // 初始化状态指示按钮为空
    , m_isLoginStatusActive(false)     // 初始化登录状态为失效
    // 🎯 四态按钮管理初始化
    , m_buttonState(ExportButtonState::Disabled)
    , m_clickInProgress(0)
    , m_lastClickTime(0)
{
    // 初始化状态栏控件
    setupStatusWidgets();
    setupExportControls();
    setupSystemInfo();

    // 布局状态栏
    arrangeStatusBarItems();

    // Martin Fowler重构：移除ExportStateManager信号连接，改用MergedExportManager的GlobalExportState
    // connect(nullptr, SIGNAL(stateChanged(ExportStateManager::ExportState)),
    //         this, SLOT(updateExportButtonState()));
    // connect(nullptr, SIGNAL(progressUpdated(const ExportStateManager::ExportProgress&)),
    //         this, SLOT(updateExportProgress(const ExportStateManager::ExportProgress&)));

    // 🔥 立即响应文件处理状态变化信号
    if (m_mainWindow) {
        // 连接文件处理状态变化信号，启动同步定时器
        connect(m_mainWindow, &MainWindow::fileProcessingStateChanged,
                this, [this](bool isProcessing) {
                    if (isProcessing) {
                        startFileProcessingSync();
                    }
                });
    }

    // 设置更新定时器
    m_updateTimer = new QTimer(this);
    m_updateTimer->setInterval(1000); // 每秒更新一次
    connect(m_updateTimer, &QTimer::timeout, this, &StatusBarManager::updateStatusDisplay);
    m_updateTimer->start();

    // 🔍 调试：添加进度监控定时器，检测UI卡住问题
    m_progressMonitorTimer = new QTimer(this);
    m_progressMonitorTimer->setInterval(3000); // 每3秒检查一次，更及时发现卡住
    m_lastProgressTime = QDateTime::currentMSecsSinceEpoch();
    m_lastProgressValue = 0;
    connect(m_progressMonitorTimer, &QTimer::timeout, this, [this]() {
        qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
        qint64 timeSinceLastProgress = currentTime - m_lastProgressTime;

        if (timeSinceLastProgress > 5000) { // 超过5秒没有进度更新，更快检测
            qWarning() << "[StatusBarManager] ⚠️ UI进度卡住警告！";
            qWarning() << "  - 上次进度时间:" << m_lastProgressTime;
            qWarning() << "  - 当前时间:" << currentTime;
            qWarning() << "  - 停滞时间:" << timeSinceLastProgress << "ms";
            qWarning() << "  - 上次进度值:" << m_lastProgressValue << "%";
            qWarning() << "  - 进度条可见性:" << (m_exportProgressBar ? m_exportProgressBar->isVisible() : false);
            qWarning() << "  - 进度条当前值:" << (m_exportProgressBar ? m_exportProgressBar->value() : -1);

            // 🔧 修复：尝试强制刷新UI
            if (m_exportProgressBar) {
                m_exportProgressBar->repaint();
                QApplication::processEvents(QEventLoop::AllEvents, 10);
            }
        }
    });
    m_progressMonitorTimer->start();

    // 设置文件处理状态同步定时器 - 修复：只在有文件处理活动时运行
    m_fileProcessingSyncTimer = new QTimer(this);
    m_fileProcessingSyncTimer->setInterval(500); // 每500ms同步一次文件处理状态
    connect(m_fileProcessingSyncTimer, &QTimer::timeout, this, &StatusBarManager::syncFileProcessingState);
    // 注意：定时器初始不启动，只在需要时启动

    // Martin Fowler重构：初始化文件夹闪烁定时器
    m_folderBlinkTimer = new QTimer(this);
    m_folderBlinkTimer->setInterval(600); // 心跳频率，约1秒一次
    connect(m_folderBlinkTimer, &QTimer::timeout, this, &StatusBarManager::onFolderBlinkTimeout);

    // 安装事件过滤器以监听状态栏大小变化
    m_statusBar->installEventFilter(this);

}

StatusBarManager::~StatusBarManager()
{
}

// 设置流式导出管理器
void StatusBarManager::setStreamingExportManager(StreamingExportManager* exportManager)
{
    if (m_streamingExportManager) {
        // 断开旧的连接
        disconnect(m_streamingExportManager, nullptr, this, nullptr);
    }
    
    m_streamingExportManager = exportManager;
    
    if (m_streamingExportManager) {
        
        // 连接进度更新信号 (新格式：只显示百分比进度，忽略文字信息)
        connect(m_streamingExportManager, &StreamingExportManager::progressUpdated,
                this, [this](int currentProgress, int totalProgress, const QString& statusText) {
                    // 🔍 调试：记录信号接收时间戳
                    qint64 signalReceiveTime = QDateTime::currentMSecsSinceEpoch();

                    // 🔧 简化：只显示百分比进度，忽略所有文字信息
                    updateExportProgress(currentProgress, totalProgress, QString());  // 空字符串，不显示任何文字

                    qint64 processTime = QDateTime::currentMSecsSinceEpoch();
                });
        
        // 🎯 流式导出完成信号已移至下面统一处理，确保按钮状态正确恢复
        
        // 连接导出失败信号
        connect(m_streamingExportManager, &StreamingExportManager::exportFailed,
                this, [this](const QString& error) {
                    emit exportFailedToast(error);
                });
        
        // 连接导出取消信号
        connect(m_streamingExportManager, &StreamingExportManager::exportCancelled,
                this, [this]() {
                    showExportCancelled();
                });
        

        // 🎯 连接StreamingExportManager的状态信号
        connect(m_streamingExportManager, &StreamingExportManager::exportStarted,
                [=](int totalFiles, const QString& outputPath) {
                    setExportButtonState(ExportButtonState::Exporting);
                    showExportStarted(totalFiles, "开始导出...");
                });

        connect(m_streamingExportManager, &StreamingExportManager::exportCompleted,
                [=](const QString& outputPath) {

                    // 保存导出路径用于其他功能
                    m_lastExportPath = outputPath;

                    // 开始文件夹图标闪烁（UI效果）
                    m_folderBlinkCount = 0;
                    m_folderBlinkTimer->start();

                    // 恢复按钮状态
                    updateExportButtonStateByFileAvailability(m_currentStatus.totalFiles() > 0);
                });

        connect(m_streamingExportManager, &StreamingExportManager::exportFailed,
                [=](const QString& error) {
                    updateExportButtonStateByFileAvailability(m_currentStatus.totalFiles() > 0);
                });

        connect(m_streamingExportManager, &StreamingExportManager::exportCancelled,
                [=]() {
                    updateExportButtonStateByFileAvailability(m_currentStatus.totalFiles() > 0);
                });
    }
}

// Martin Fowler重构：移除setFileBrowserToExportManager方法（不再需要）

void StatusBarManager::setupStatusWidgets()
{
    // 版本信息容器（最左侧）
    m_versionWidget = new QWidget();
    QHBoxLayout* versionLayout = new QHBoxLayout(m_versionWidget);
    versionLayout->setContentsMargins(8, 4, 8, 4);
    versionLayout->setSpacing(6);

    // 版本信息标签 - 显示当前版本或升级信息
    m_versionLabel = new QLabel();
    m_versionLabel->setText(LimeReader::AppVersion::getVersionWithPrefix());  // 初始显示当前版本
    m_versionLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    m_versionLabel->setStyleSheet(
        "QLabel { "
        "    color: #8E8E93; "  // 平时灰色
        "    font-size: 12px; "
        "    font-weight: 500; "
        "    padding: 2px 6px; "
        "    background-color: rgba(142, 142, 147, 0.1); "
        "    border-radius: 4px; "
        "}"
    );

    // 更新图标按钮（初始隐藏）
    m_updateIconButton = new QPushButton();
    m_updateIconButton->setFixedSize(20, 20);
    m_updateIconButton->setVisible(false);  // 初始隐藏
    m_updateIconButton->setIcon(createUpdateIcon());
    m_updateIconButton->setIconSize(QSize(16, 16));
    m_updateIconButton->setStyleSheet(
        "QPushButton { "
        "    border: none; "
        "    background: transparent; "
        "    border-radius: 2px; "
        "    padding: 2px; "
        "} "
        "QPushButton:hover { "
        "    background-color: rgba(0, 122, 255, 0.1); "
        "} "
        "QPushButton:pressed { "
        "    background-color: rgba(0, 122, 255, 0.2); "
        "}"
    );

    // 连接更新图标按钮点击信号
    connect(m_updateIconButton, &QPushButton::clicked, this, &StatusBarManager::onUpdateIconButtonClicked);

    versionLayout->addWidget(m_versionLabel);
    versionLayout->addWidget(m_updateIconButton);

    // 当前全局页码标签（用于验证）- Apple风格
    m_currentGlobalPageLabel = new QLabel();
    m_currentGlobalPageLabel->setText("全局页码: 0");
    m_currentGlobalPageLabel->setFixedWidth(120);   // 固定宽度
    m_currentGlobalPageLabel->setAlignment(Qt::AlignCenter);
    m_currentGlobalPageLabel->setStyleSheet(
        "QLabel { "
        "    color: #8E8E93; "  // Apple Secondary Label
        "    font-size: 12px; "
        "    font-weight: 400; "
        "    padding: 2px 6px; "
        "    background-color: rgba(142, 142, 147, 0.1); "  // 淡灰色背景
        "    border-radius: 4px; "
        "}"
    );

    // 文件总页数标签 - Apple风格
    m_totalPagesLabel = new QLabel();
    m_totalPagesLabel->setText("共 0 页");
    m_totalPagesLabel->setFixedWidth(80);   // 固定宽度
    m_totalPagesLabel->setAlignment(Qt::AlignCenter);
    m_totalPagesLabel->setStyleSheet(
        "QLabel { "
        "    color: #8E8E93; "  // Apple Secondary Label
        "    font-size: 12px; "
        "    font-weight: 400; "
        "    padding: 2px 6px; "
        "    background-color: rgba(142, 142, 147, 0.1); "
        "    border-radius: 4px; "
        "}"
    );

    // 设置信息标签 - Apple风格
    m_settingsInfoLabel = new QLabel();
    m_settingsInfoLabel->setText("DPI: 150");
    m_settingsInfoLabel->setFixedWidth(100);  // 固定宽度
    m_settingsInfoLabel->setAlignment(Qt::AlignCenter);
    m_settingsInfoLabel->setStyleSheet(
        "QLabel { "
        "    color: #8E8E93; "  // Apple Secondary Label
        "    font-size: 12px; "
        "    font-weight: 400; "
        "    padding: 2px 6px; "
        "    background-color: rgba(142, 142, 147, 0.1); "
        "    border-radius: 4px; "
        "}"
    );

    // 缓存信息标签 - Apple风格，增加宽度
    m_cacheInfoLabel = new QLabel();
    m_cacheInfoLabel->setText("缓存: 0 MB");
    m_cacheInfoLabel->setFixedWidth(140);   // 增加宽度以显示更多缓存信息
    m_cacheInfoLabel->setAlignment(Qt::AlignCenter);
    m_cacheInfoLabel->setStyleSheet(
        "QLabel { "
        "    color: #8E8E93; "  // Apple Secondary Label
        "    font-size: 12px; "
        "    font-weight: 400; "
        "    padding: 2px 8px; "  // 增加内边距
        "    background-color: rgba(142, 142, 147, 0.1); "
        "    border-radius: 4px; "
        "}"
    );

    // 系统状态标签
    m_systemStatusLabel = new QLabel();
    m_systemStatusLabel->setText(getSystemInfo());
    m_systemStatusLabel->setFixedWidth(120);   // 增加宽度以显示系统信息
    m_systemStatusLabel->setAlignment(Qt::AlignCenter);
    m_systemStatusLabel->setStyleSheet(
        "QLabel { "
        "    color: #8E8E93; "  // Apple Secondary Label
        "    font-size: 11px; "
        "    font-weight: 400; "
        "    padding: 2px 6px; "
        "    background-color: rgba(142, 142, 147, 0.1); "
        "    border-radius: 4px; "
        "}"
    );

    // 创建切换按钮 - Apple风格设计
    m_toggleFileListButton = new QPushButton();
    m_toggleFileListButton->setFixedSize(20, 20);
    m_toggleFileListButton->setIcon(createSplitPanelIcon(true));  // 左侧激活的图标
    m_toggleFileListButton->setToolTip("切换文件列表面板");
    m_toggleFileListButton->setStyleSheet(
        "QPushButton { "
        "    border: none; "
        "    background: transparent; "
        "    border-radius: 4px; "
        "    padding: 2px; "
        "} "
        "QPushButton:hover { "
        "    background-color: rgba(0, 122, 255, 0.1); "  // Apple Blue with transparency
        "} "
        "QPushButton:pressed { "
        "    background-color: rgba(0, 122, 255, 0.2); "
        "}"
    );

    m_togglePreviewButton = new QPushButton();
    m_togglePreviewButton->setFixedSize(20, 20);
    m_togglePreviewButton->setIcon(createSplitPanelIcon(false)); // 右侧激活的图标
    m_togglePreviewButton->setToolTip("切换预览面板");
    m_togglePreviewButton->setStyleSheet(
        "QPushButton { "
        "    border: none; "
        "    background: transparent; "
        "    border-radius: 4px; "
        "    padding: 2px; "
        "} "
        "QPushButton:hover { "
        "    background-color: rgba(0, 122, 255, 0.1); "  // Apple Blue with transparency
        "} "
        "QPushButton:pressed { "
        "    background-color: rgba(0, 122, 255, 0.2); "
        "}"
    );

    // 连接切换按钮信号
    connect(m_toggleFileListButton, &QPushButton::clicked, this, &StatusBarManager::onToggleFileListClicked);
    connect(m_togglePreviewButton, &QPushButton::clicked, this, &StatusBarManager::onTogglePreviewClicked);

    // 创建登录状态指示按钮（最右侧）
    m_statusIndicatorButton = new QPushButton();
    m_statusIndicatorButton->setFixedSize(16, 16);  // 圆形按钮
    m_statusIndicatorButton->setToolTip("登录状态指示");
    m_statusIndicatorButton->setIcon(createStatusIndicatorIcon(false)); // 初始为灰色
    m_statusIndicatorButton->setIconSize(QSize(12, 12));
    m_statusIndicatorButton->setStyleSheet(
        "QPushButton { "
        "    border: none; "
        "    background: transparent; "
        "    border-radius: 8px; "  // 圆形
        "    padding: 2px; "
        "} "
        "QPushButton:hover { "
        "    background-color: rgba(0, 122, 255, 0.1); "
        "} "
        "QPushButton:pressed { "
        "    background-color: rgba(0, 122, 255, 0.2); "
        "}"
    );

    // 🎯 初始化导出按钮状态（四态管理）
    if (m_oneClickExportButton) {
        setExportButtonState(ExportButtonState::Disabled);  // 初始为禁用状态
    }

}

void StatusBarManager::setupExportControls()
{
    // 创建导出控制容器
    m_exportControlWidget = new QWidget();
    QHBoxLayout* layout = new QHBoxLayout(m_exportControlWidget);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(5);

    // 一键导出按钮 - 初始为不可用状态（优雅浅灰色）
    m_oneClickExportButton = new QPushButton("一键导出");
    m_oneClickExportButton->setMaximumHeight(20);
    m_oneClickExportButton->setIcon(createPdfExportIcon());
    m_oneClickExportButton->setEnabled(false);  // 初始不可用
    m_oneClickExportButton->setStyleSheet(
        "QPushButton { "
        "    background-color: #C7C7CC; "  // 标准不可用灰色
        "    color: #8E8E93; "
        "    border: none; "
        "    border-radius: 2px; "  // 稍微不圆的圆角
        "    padding: 2px 8px; "  // 缩小内边距
        "    font-weight: 500; "  // 中等字重
        "    font-size: 12px; "
        "} "
        "QPushButton:disabled { "
        "    background-color: #8E8E93; "  // Apple Gray
        "    color: #C7C7CC; "
        "    transform: none; "
        "}"
    );
    connect(m_oneClickExportButton, &QPushButton::clicked, this, &StatusBarManager::handleExportButtonClick);

    // 导出设置按钮 - 已移除
    // m_exportSettingsButton = new QPushButton("设置");
    // ...

    // 导出进度条 - 使用Apple风格设计
    m_exportProgressBar = new QProgressBar();
    m_exportProgressBar->setMaximumHeight(16);
    m_exportProgressBar->setMinimumWidth(120);
    m_exportProgressBar->setVisible(false);
    m_exportProgressBar->setStyleSheet(
        "QProgressBar { "
        "    border: 1px solid #E5E5EA; "  // 更淡的边框
        "    border-radius: 8px; "  // 现代圆角
        "    text-align: center; "
        "    background-color: #F9F9FB; "  // 更清爽的背景
        "    color: #1D1D1F; "  // Apple Label
        "    font-size: 11px; "
        "    font-weight: 600; "  // 稍微加粗字体
        "} "
        "QProgressBar::chunk { "
        "    background: qlineargradient(x1:0, y1:0, x2:1, y2:0, "
        "        stop:0 #4A90E2, stop:0.5 #87CEEB, stop:1 #B0E0E6); "  // iOS蓝到更白亮蓝的渐变
        "    border-radius: 7px; "
        "    margin: 2px; "  // 内边距，让进度条更优雅
        "}"
    );

    // 文件夹图标按钮
    m_folderIconButton = new QPushButton();
    m_folderIconButton->setFixedSize(20, 20);
    m_folderIconButton->setIcon(createFolderIcon());
    m_folderIconButton->setToolTip("打开PDF导出文件夹");
    m_folderIconButton->setStyleSheet(
        "QPushButton { "
        "    border: none; "
        "    background: transparent; "
        "    border-radius: 2px; "
        "    padding: 2px; "
        "} "
        "QPushButton:hover { "
        "    background-color: rgba(0, 122, 255, 0.1); "
        "} "
        "QPushButton:pressed { "
        "    background-color: rgba(0, 122, 255, 0.2); "
        "}"
    );
    connect(m_folderIconButton, &QPushButton::clicked, this, &StatusBarManager::onFolderIconClicked);

    // Martin Fowler重构：去掉文字提示区域，Less is More
    // 移除m_exportStatusLabel以简化UI

    // 先添加进度条，再添加按钮，最后添加文件夹图标
    layout->addWidget(m_exportProgressBar);
    layout->addWidget(m_oneClickExportButton);
    layout->addWidget(m_folderIconButton);
    // layout->addWidget(m_exportSettingsButton); // 已移除配置按钮

}

void StatusBarManager::setupSystemInfo()
{
    // 创建系统信息容器
    m_systemInfoWidget = new QWidget();
    QHBoxLayout* layout = new QHBoxLayout(m_systemInfoWidget);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(5);

    // 创建在线版本按钮
    m_onlineVersionButton = new QPushButton();
    m_onlineVersionButton->setText("");  // 移除文字
    m_onlineVersionButton->setToolTip("打开在线版本: https://ctdy123.com");
    m_onlineVersionButton->setFixedSize(20, 20);  // 与文件夹按钮一致的尺寸

    // 设置地球仪图标
    m_onlineVersionButton->setIcon(createGlobeIcon());
    m_onlineVersionButton->setIconSize(QSize(16, 16));

    // 设置与文件夹按钮一致的样式
    m_onlineVersionButton->setStyleSheet(
        "QPushButton { "
        "    border: none; "
        "    background: transparent; "
        "    border-radius: 2px; "
        "    padding: 2px; "
        "} "
        "QPushButton:hover { "
        "    background-color: rgba(0, 122, 255, 0.1); "
        "} "
        "QPushButton:pressed { "
        "    background-color: rgba(0, 122, 255, 0.2); "
        "}"
    );

    // 连接点击信号
    connect(m_onlineVersionButton, &QPushButton::clicked, this, &StatusBarManager::openOnlineVersion);
    
    layout->addWidget(m_onlineVersionButton);

    // 缓存管理按钮 - 已移除
    // m_cacheManagementButton = new QPushButton("缓存");
    // ...

    // layout->addWidget(m_cacheManagementButton); // 已移除缓存按钮

}

void StatusBarManager::arrangeStatusBarItems()
{
    // 清除现有项目
    m_statusBar->clearMessage();

    // 1. 添加版本信息组件到最左侧
    m_statusBar->addWidget(m_versionWidget, 0);

    // 2. 添加全局页码和总页数显示
    m_statusBar->addWidget(m_currentGlobalPageLabel, 0);
    m_statusBar->addWidget(m_totalPagesLabel, 0);

    // 3. 创建设置和缓存信息容器（临时隐藏）
    // QWidget* infoContainer = new QWidget();
    // QHBoxLayout* infoLayout = new QHBoxLayout(infoContainer);
    // infoLayout->setContentsMargins(4, 4, 4, 4);
    // infoLayout->setSpacing(6);

    // infoLayout->addWidget(m_settingsInfoLabel);
    // infoLayout->addWidget(m_cacheInfoLabel);

    // 添加信息容器到状态栏
    // m_statusBar->addWidget(infoContainer, 0);

    // 4. 添加弹簧以推送右侧控件
    m_statusBar->addWidget(new QLabel(), 1); // 弹簧控件

    // 5. 添加导出控制控件（右侧）
    m_statusBar->addPermanentWidget(m_exportControlWidget, 0);

    // 6. 创建状态面板容器，包含系统状态和切换按钮
    QWidget* statusPanel = new QWidget();
    QHBoxLayout* statusLayout = new QHBoxLayout(statusPanel);
    statusLayout->setContentsMargins(4, 4, 8, 4);
    statusLayout->setSpacing(4);

    statusLayout->addWidget(m_systemStatusLabel);
    statusLayout->addWidget(m_toggleFileListButton);
    statusLayout->addWidget(m_togglePreviewButton);

    // 添加系统信息控件（在切换按钮前）
    m_statusBar->addPermanentWidget(m_systemInfoWidget, 0);

    // 添加状态面板到状态栏（最右侧）
    m_statusBar->addPermanentWidget(statusPanel, 0);

    // 添加登录状态指示按钮到状态栏（最最右侧）
    m_statusBar->addPermanentWidget(m_statusIndicatorButton, 0);

    // 设置隐藏优先级列表（从右到左，最先隐藏到最后隐藏）
    m_hidingPriorityWidgets.clear();
    m_hidingPriorityWidgets.append(statusPanel);               // 1. 状态面板（最右侧）
    m_hidingPriorityWidgets.append(m_systemInfoWidget);        // 2. 系统信息控件
    // m_hidingPriorityWidgets.append(m_cacheInfoLabel);          // 3. 缓存信息（已隐藏）
    // m_hidingPriorityWidgets.append(m_settingsInfoLabel);       // 4. DPI设置（已隐藏）
    // m_hidingPriorityWidgets.append(infoContainer);             // 5. 信息容器（已隐藏）
    m_hidingPriorityWidgets.append(m_versionWidget);           // 6. 版本信息（最左侧，最后隐藏）
    m_hidingPriorityWidgets.append(m_totalPagesLabel);         // 5. 文件总页数
    m_hidingPriorityWidgets.append(m_currentGlobalPageLabel);  // 6. 当前全局页码

    // 初始调用响应式布局更新
    QTimer::singleShot(0, this, &StatusBarManager::updateResponsiveLayout);
}

bool StatusBarManager::eventFilter(QObject* watched, QEvent* event)
{
    if (watched == m_statusBar && event->type() == QEvent::Resize) {
        updateResponsiveLayout();
    }
    return QObject::eventFilter(watched, event);
}

void StatusBarManager::updateResponsiveLayout()
{
    if (!m_statusBar || !m_statusBar->layout()) return;

    int availableWidth = m_statusBar->width();
    const int STATUS_BAR_SPACING = m_statusBar->layout()->spacing();

    // 1. 首先确保所有控件都可见（窗口扩大时能重新显示）
    for (QWidget* widget : m_hidingPriorityWidgets) {
        widget->setVisible(true);
    }

    // 2. 计算当前所有可见控件的总宽度
    int currentTotalWidth = 0;
    QList<QWidget*> allWidgetsInLayoutOrder;

    QLayout* layout = m_statusBar->layout();
    if (layout) {
        for (int i = 0; i < layout->count(); ++i) {
            QLayoutItem* item = layout->itemAt(i);
            if (item && item->widget()) {
                QWidget* widget = item->widget();
                if (widget->isVisible()) {
                    allWidgetsInLayoutOrder.append(widget);
                }
            }
        }
    }

    // 计算所有可见控件的宽度和间距
    for (int i = 0; i < allWidgetsInLayoutOrder.size(); ++i) {
        currentTotalWidth += allWidgetsInLayoutOrder[i]->sizeHint().width();
        if (i < allWidgetsInLayoutOrder.size() - 1) {
            currentTotalWidth += STATUS_BAR_SPACING;
        }
    }

    // 3. 如果总宽度超过可用宽度，按优先级从右到左隐藏控件
    for (QWidget* widgetToHide : m_hidingPriorityWidgets) {
        if (currentTotalWidth > availableWidth && widgetToHide->isVisible()) {
            widgetToHide->setVisible(false);

            // 重新计算总宽度
            currentTotalWidth = 0;
            allWidgetsInLayoutOrder.clear();

            if (layout) {
                for (int i = 0; i < layout->count(); ++i) {
                    QLayoutItem* item = layout->itemAt(i);
                    if (item && item->widget()) {
                        QWidget* widget = item->widget();
                        if (widget->isVisible()) {
                            allWidgetsInLayoutOrder.append(widget);
                        }
                    }
                }
            }

            for (int i = 0; i < allWidgetsInLayoutOrder.size(); ++i) {
                currentTotalWidth += allWidgetsInLayoutOrder[i]->sizeHint().width();
                if (i < allWidgetsInLayoutOrder.size() - 1) {
                    currentTotalWidth += STATUS_BAR_SPACING;
                }
            }
        } else if (currentTotalWidth <= availableWidth) {
            // 如果当前宽度适合，则停止隐藏
            break;
        }
    }
}

void StatusBarManager::updateStatus(const StatusBarInfo& statusInfo)
{
    m_currentStatus = statusInfo;


    // ExportStateManager已移除，状态管理统一由MergedExportManager的GlobalExportState处理
}

void StatusBarManager::updateFileInfo(int currentFileIndex, int totalFiles, const QString& fileName)
{
    StatusBarInfo newStatus(currentFileIndex, totalFiles, fileName);
    updateStatus(newStatus);
}

// Martin Fowler重构：添加全局页码显示用于验证

void StatusBarManager::updateCurrentGlobalPage(int currentGlobalPage, int totalPages)
{
    if (totalPages > 0) {
        m_currentGlobalPageLabel->setText(QString("全局页码: %1").arg(currentGlobalPage));
    } else {
        m_currentGlobalPageLabel->setText("全局页码: 0");
    }
}

void StatusBarManager::updateTotalPages(int totalPages)
{
    if (totalPages > 0) {
        m_totalPagesLabel->setText(QString("共 %1 页").arg(totalPages));
    } else {
        m_totalPagesLabel->setText("共 0 页");
    }
}

void StatusBarManager::updateProcessingSettings(const ProcessingSettings& settings)
{
    // Martin Fowler重构：Move Method - 使用StatusBarFormatter
    QString settingsInfo = StatusBarFormatter::formatExportSettings(settings.standardDPI, settings.getDPIDescription());
    m_settingsInfoLabel->setText(settingsInfo);
}

void StatusBarManager::updateCacheStatus(qint64 cacheSize, int cacheCount)
{
    // Martin Fowler重构：Move Method - 使用StatusBarFormatter
    QString cacheInfo = StatusBarFormatter::formatCacheInfo(cacheSize, cacheCount);
    m_cacheInfoLabel->setText(cacheInfo);
}

void StatusBarManager::updateSystemStatus(const QString& status)
{
    m_systemStatusLabel->setText(status);

    // 🔧 修复：只在非导出状态下保存原始系统信息
    if (!status.contains("导出") && !status.contains("完成")) {
        m_originalSystemInfo = status;
    }
}

void StatusBarManager::updateExportProgress(int completedFiles, int totalFiles, const QString& status)
{
    // 🔍 调试：记录接收进度的时间戳
    qint64 receiveTime = QDateTime::currentMSecsSinceEpoch();
    // 🔧 简化：忽略状态文本，只显示进度条百分比

    // 🔍 更新进度监控时间戳
    m_lastProgressTime = receiveTime;
    m_lastProgressValue = (totalFiles == 100) ? completedFiles : (completedFiles * 100) / totalFiles;

    // 更新进度条（修复：统一使用百分比模式）
    if (m_exportProgressBar) {
        m_exportProgressBar->setVisible(true);

        // 🔧 修复：确保进度条始终使用百分比模式（0-100）
        if (m_exportProgressBar->maximum() != 100) {
            qint64 resetTime = QDateTime::currentMSecsSinceEpoch();
            m_exportProgressBar->setRange(0, 100);
        }

        if (totalFiles > 0) {
            int progressValue = 0;
            // StreamingExportManager发送的是百分比进度，直接使用
            if (totalFiles == 100) {
                progressValue = completedFiles;
            } else {
                // 兼容模式：计算百分比（保留用于其他可能的调用）
                progressValue = (completedFiles * 100) / totalFiles;
            }

            // 🔍 调试：记录UI更新前的时间戳
            qint64 uiUpdateTime = QDateTime::currentMSecsSinceEpoch();

            // 设置进度值
            m_exportProgressBar->setValue(progressValue);

            // 🔧 修复：强制每次进度更新都刷新UI，防止信号积压
            qint64 refreshTime = QDateTime::currentMSecsSinceEpoch();
            m_exportProgressBar->update();

            // 🔧 修复：确保进度条显示百分比文字
            if (m_exportProgressBar->format().isEmpty()) {
                m_exportProgressBar->setFormat("%p%");  // 显示百分比文字
            }

            // 🔧 关键修复：使用更激进的UI刷新策略
            // 1. 立即处理所有待处理事件
            // 2. 使用更短的刷新间隔
            // 3. 强制重绘进度条
            m_exportProgressBar->repaint();
            QApplication::processEvents(QEventLoop::AllEvents, 10); // 最多处理10ms


        }
    }

    // 🔧 简化：导出时只显示进度条百分比，不更新任何其他文字信息
    // 系统信息面板保持原有内容不变
}

// ✅ 清理：移除updateDetailedExportProgress()方法（不再使用三阶段进度）
// 现在统一使用updateExportProgress()显示进度

void StatusBarManager::showExportStarted(int totalFiles, const QString& status)
{

    // ExportStateManager已移除，直接显示导出开始UI

    // 🔧 修复：显示进度条但不重置为0，让StreamingExportManager控制进度
    if (m_exportProgressBar) {
        m_exportProgressBar->setVisible(true);
        // 🔧 修复：确保进度条使用正确的范围
        if (m_exportProgressBar->maximum() != 100) {
            m_exportProgressBar->setRange(0, 100);
        }
        // 🔧 修复：确保进度条显示百分比文字
        if (m_exportProgressBar->format().isEmpty()) {
            m_exportProgressBar->setFormat("%p%");  // 显示百分比文字
        }
        // 不设置setValue(0)，让StreamingExportManager的第一个进度信号来控制
    }

    // Martin Fowler重构：移除文字提示区域，Less is More
    // 使用进度条显示状态信息即可，不需要文字状态提示

}

void StatusBarManager::showExportCompleted(const QString& outputPath)
{
    // Martin Fowler重构：移除业务逻辑，专注UI显示
    // 业务逻辑已移至ExportStateManager

    // 保存导出路径用于其他功能
    m_lastExportPath = outputPath;

    // 开始文件夹图标闪烁（UI效果）
    m_folderBlinkCount = 0;
    m_folderBlinkTimer->start();

    // Martin Fowler重构：移除文字提示区域，Less is More
    // 文件夹闪烁和Toast提示已足够，不需要文字状态
}

void StatusBarManager::showExportFailed(const QString& error)
{
    // Martin Fowler重构：移除业务逻辑，专注UI显示
    // 业务逻辑已移至ExportStateManager，包括Toast发送

    // Martin Fowler重构：移除文字提示区域，Less is More
    // Toast提示已足够，不需要文字状态
}

void StatusBarManager::showExportCancelled()
{

    // 🎯 四态管理：使用四态管理器恢复按钮状态，而不是直接操作UI
    updateExportButtonStateByFileAvailability(m_currentStatus.totalFiles() > 0);

    // 🔧 修复：隐藏进度条但保留格式，避免后续显示问题
    if (m_exportProgressBar) {
        m_exportProgressBar->setValue(0);
        // 🔧 修复：不清除格式文本，保留百分比格式供下次使用
        // m_exportProgressBar->setFormat(""); // 移除这行，避免破坏格式
        m_exportProgressBar->setVisible(false);
    }

}

void StatusBarManager::showExportControls(bool show)
{
    m_exportControlWidget->setVisible(show);
}


void StatusBarManager::setExportAvailable(bool canExport)
{

    // 🎯 使用四态管理：根据文件可用性更新按钮状态
    updateExportButtonStateByFileAvailability(canExport);

}


void StatusBarManager::onUpdateButtonClicked()
{
    emit updateRequested();
}

void StatusBarManager::setUpdateButtonState(bool hasUpdate)
{
    // 此方法已弃用，更新状态现在通过updateVersionInfo方法处理
    Q_UNUSED(hasUpdate)
}

void StatusBarManager::onToggleFileListClicked()
{
    emit toggleFileListRequested();
}

void StatusBarManager::debugExportButtonState()
{
    
    
    
}

void StatusBarManager::debugSimpleExportState()
{
}

// ===== 🎯 四态按钮管理实现（新增） =====

// 设置按钮状态（公共接口）
void StatusBarManager::setExportButtonState(ExportButtonState state)
{
    if (!canTransitionTo(state)) {
        return;
    }

    m_buttonState = state;
    updateButtonUI(state);
}

// 获取当前按钮状态
StatusBarManager::ExportButtonState StatusBarManager::getExportButtonState() const
{
    return m_buttonState;
}

// 根据文件可用性更新按钮状态
void StatusBarManager::updateExportButtonStateByFileAvailability(bool hasFiles)
{

    // 🎯 关键修复：取消操作完成后也允许状态更新
    if (m_buttonState == ExportButtonState::Available ||
        m_buttonState == ExportButtonState::Disabled ||
        m_buttonState == ExportButtonState::Exporting ||
        m_buttonState == ExportButtonState::Cancelling) {

        ExportButtonState newState = hasFiles ? ExportButtonState::Available : ExportButtonState::Disabled;
        setExportButtonState(newState);
    } else {
    }

}

// 统一的按钮点击处理
void StatusBarManager::handleExportButtonClick()
{

    // 第1层：防抖检查
    if (!shouldAllowClick()) {
        return;
    }

    // 第2层：重复点击防护
    if (!m_clickInProgress.testAndSetOrdered(0, 1)) {
        return;
    }

    // 第3层：状态转换验证
    ExportButtonState currentState = m_buttonState;

    // 处理用户点击
    processUserClick(currentState);

    // 重置点击标志
    m_clickInProgress.storeRelease(0);

}

// 状态转换验证
bool StatusBarManager::canTransitionTo(ExportButtonState newState) const
{
    ExportButtonState current = m_buttonState;

    switch (current) {
        case ExportButtonState::Disabled:
            return newState == ExportButtonState::Available;  // 只能从禁用变为可用

        case ExportButtonState::Available:
            return newState == ExportButtonState::Exporting || newState == ExportButtonState::Disabled;

        case ExportButtonState::Exporting:
            return newState == ExportButtonState::Cancelling || newState == ExportButtonState::Available;

        case ExportButtonState::Cancelling:
            return newState == ExportButtonState::Available || newState == ExportButtonState::Disabled;
    }
    return false;
}

// 更新按钮UI
void StatusBarManager::updateButtonUI(ExportButtonState state)
{
    if (!m_oneClickExportButton) {
        return;
    }

    QString text = getButtonText(state);
    QString style = getButtonStyle(state);
    bool enabled = (state != ExportButtonState::Disabled && state != ExportButtonState::Cancelling);

    m_oneClickExportButton->setText(text);
    m_oneClickExportButton->setEnabled(enabled);
    m_oneClickExportButton->setStyleSheet(style);

}

// 防抖检查
bool StatusBarManager::shouldAllowClick() const
{
    quint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    return (currentTime - m_lastClickTime >= CLICK_DEBOUNCE_MS);
}

// 处理用户点击逻辑
void StatusBarManager::processUserClick(ExportButtonState currentState)
{
    // 更新点击时间戳
    m_lastClickTime = QDateTime::currentMSecsSinceEpoch();

    switch (currentState) {
        case ExportButtonState::Available:

            // 立即切换到导出状态，提供即时反馈
            setExportButtonState(ExportButtonState::Exporting);

            // 发出导出请求信号
            emit oneClickExportRequested();
            break;

        case ExportButtonState::Exporting:

            // 切换到取消状态
            setExportButtonState(ExportButtonState::Cancelling);

            // 调用取消方法
            if (m_streamingExportManager) {
                m_streamingExportManager->cancelExport();
            }
            break;

        case ExportButtonState::Disabled:
            break;

        case ExportButtonState::Cancelling:
            break;
    }
}

// 获取按钮文本
QString StatusBarManager::getButtonText(ExportButtonState state) const
{
    switch (state) {
        case ExportButtonState::Available:
        case ExportButtonState::Disabled:
            return "一键导出";
        case ExportButtonState::Exporting:
            return "取消导出";
        case ExportButtonState::Cancelling:
            return "正在取消";
    }
    return "一键导出";
}

// 获取按钮样式
QString StatusBarManager::getButtonStyle(ExportButtonState state) const
{
    switch (state) {
        case ExportButtonState::Available:
            // 蓝色可用状态
            return "QPushButton { "
                   "    background-color: #007AFF; "
                   "    color: white; "
                   "    border: none; "
                   "    border-radius: 2px; "
                   "    padding: 2px 8px; "
                   "    font-weight: 500; "
                   "    font-size: 12px; "
                   "} "
                   "QPushButton:hover { "
                   "    background-color: #0056CC; "
                   "    transform: translateY(-1px); "
                   "} "
                   "QPushButton:pressed { "
                   "    background-color: #004499; "
                   "    transform: translateY(0px); "
                   "}";

        case ExportButtonState::Disabled:
            // 灰色禁用状态
            return "QPushButton { "
                   "    background-color: #C7C7CC; "
                   "    color: #8E8E93; "
                   "    border: none; "
                   "    border-radius: 2px; "
                   "    padding: 2px 8px; "
                   "    font-weight: 500; "
                   "    font-size: 12px; "
                   "} "
                   "QPushButton:disabled { "
                   "    background-color: #8E8E93; "
                   "    color: #C7C7CC; "
                   "    transform: none; "
                   "}";

        case ExportButtonState::Exporting:
            // 红色导出状态（可取消）
            return "QPushButton { "
                   "    background-color: #FF3B30; "
                   "    color: white; "
                   "    border: none; "
                   "    border-radius: 2px; "
                   "    padding: 2px 8px; "
                   "    font-weight: 500; "
                   "    font-size: 12px; "
                   "} "
                   "QPushButton:hover { "
                   "    background-color: #E62D21; "
                   "} "
                   "QPushButton:pressed { "
                   "    background-color: #D52B1F; "
                   "}";

        case ExportButtonState::Cancelling:
            // 黄色取消状态（不可点击）
            return "QPushButton { "
                   "    background-color: #FF9500; "
                   "    color: white; "
                   "    border: none; "
                   "    border-radius: 2px; "
                   "    padding: 2px 8px; "
                   "    font-weight: 500; "
                   "    font-size: 12px; "
                   "} "
                   "QPushButton:disabled { "
                   "    background-color: #CC7700; "
                   "    color: #AAAAAA; "
                   "}";
    }
    return getButtonStyle(ExportButtonState::Disabled);
}

void StatusBarManager::onTogglePreviewClicked()
{
    emit togglePreviewRequested();
}

void StatusBarManager::openOnlineVersion()
{
    QDesktopServices::openUrl(QUrl("https://ctdy123.com"));
}

// Martin Fowler重构：移除initializeFolderBlinkSystem方法（已移至构造函数）
// 已移除配置和缓存按钮的响应方法
/*
void StatusBarManager::onExportSettingsClicked()
{
    emit exportSettingsRequested();
}

void StatusBarManager::onCacheManagementClicked()
{
    emit cacheManagementRequested();
}
*/

void StatusBarManager::updateStatusDisplay()
{
    // Martin Fowler重构：移除checkExportReadiness调用（由CustomFileBrowser处理）
}


// Martin Fowler重构：新增方法 - 处理导出进度更新
// void StatusBarManager::updateExportProgress(const ExportStateManager::ExportProgress& progress)
// 方法已移除，因为ExportStateManager已删除。现在使用简化的updateExportProgress(int, int, QString)版本


// Martin Fowler重构：Move Method - 格式化方法已迁移到StatusBarFormatter
// 这些方法现在位于 statusbarformatter.cpp 中

QIcon StatusBarManager::createPdfExportIcon() const
{
    QPixmap pixmap(16, 16);
    pixmap.fill(Qt::transparent);

    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制PDF文档图标
    // 文档背景
    painter.setBrush(QBrush(QColor(240, 240, 240)));
    painter.setPen(QPen(QColor(120, 120, 120), 1));
    painter.drawRoundedRect(2, 1, 10, 13, 1, 1);

    // 文档右上角折叠
    painter.setBrush(QBrush(QColor(200, 200, 200)));
    painter.setPen(Qt::NoPen);
    QPainterPath cornerPath;
    cornerPath.moveTo(10, 1);
    cornerPath.lineTo(12, 3);
    cornerPath.lineTo(10, 3);
    cornerPath.closeSubpath();
    painter.drawPath(cornerPath);

    // PDF文字
    painter.setPen(QPen(QColor(220, 53, 69), 1));
    painter.setFont(QFont("Arial", 5, QFont::Bold));
    painter.drawText(QRect(3, 7, 8, 4), Qt::AlignCenter, "PDF");

    // 导出箭头
    painter.setPen(QPen(QColor(70, 130, 180), 2));
    painter.drawLine(13, 8, 15, 8);
    painter.drawLine(14, 7, 15, 8);
    painter.drawLine(14, 9, 15, 8);

    return QIcon(pixmap);
}

QIcon StatusBarManager::createSplitPanelIcon(bool leftActive) const
{
    QPixmap pixmap(16, 16);
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing);
    
    // 绘制分割面板图标 - 确保两个按钮大小和比例完全一致
    QRect iconRect(2, 3, 12, 10);
    
    // 使用50:50的比例，确保黑白区域大小一致
    int leftWidth = iconRect.width() / 2;  // 左侧宽度：6像素
    int rightWidth = iconRect.width() - leftWidth;  // 右侧宽度：6像素
    
    if (leftActive) {
        // 文件列表按钮：左侧深灰色（激活），右侧浅灰色
        painter.fillRect(iconRect.left(), iconRect.top(), 
                        leftWidth, iconRect.height(), 
                        QColor(51, 51, 51));  // 深灰色 #333333
        painter.fillRect(iconRect.left() + leftWidth, iconRect.top(), 
                        rightWidth, iconRect.height(), 
                        QColor(221, 221, 221));  // 浅灰色 #DDDDDD
    } else {
        // 预览面板按钮：左侧浅灰色，右侧深灰色（激活）
        painter.fillRect(iconRect.left(), iconRect.top(), 
                        leftWidth, iconRect.height(), 
                        QColor(221, 221, 221));  // 浅灰色 #DDDDDD
        painter.fillRect(iconRect.left() + leftWidth, iconRect.top(), 
                        rightWidth, iconRect.height(), 
                        QColor(51, 51, 51));  // 深灰色rgb(110, 110, 110)
    }
    
    // 添加边框
    painter.setPen(QPen(QColor(150, 150, 150), 1));
    painter.drawRect(iconRect);
    
    return QIcon(pixmap);
}

QIcon StatusBarManager::createGlobeIcon() const
{
    QPixmap pixmap(16, 16);
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing);
    
    // 绘制地球仪图标
    QRect iconRect(2, 2, 12, 12);
    
    // 地球仪主体（圆形）
    painter.setBrush(QBrush(QColor(70, 130, 180))); // 钢蓝色
    painter.setPen(QPen(QColor(50, 100, 150), 1));
    painter.drawEllipse(iconRect);
    
    // 绘制经纬线
    painter.setPen(QPen(QColor(255, 255, 255), 1));
    
    // 经线（垂直线）
    painter.drawLine(iconRect.center().x(), iconRect.top() + 2, 
                    iconRect.center().x(), iconRect.bottom() - 2);
    
    // 纬线（水平线）
    painter.drawLine(iconRect.left() + 2, iconRect.center().y(), 
                    iconRect.right() - 2, iconRect.center().y());
    
    // 添加一条斜向的纬线
    painter.drawLine(iconRect.left() + 3, iconRect.top() + 4, 
                    iconRect.right() - 3, iconRect.top() + 4);
    painter.drawLine(iconRect.left() + 3, iconRect.bottom() - 4, 
                    iconRect.right() - 3, iconRect.bottom() - 4);
    
    return QIcon(pixmap);
}

// Martin Fowler重构：移除createBreathingIcon方法

QString StatusBarManager::getSystemInfo() const
{
    QString cpuInfo = getCpuInfo();
    QString memoryInfo = getMemoryInfo();
    return QString("%1 | %2").arg(cpuInfo, memoryInfo);
}

QString StatusBarManager::getCpuInfo() const
{
    // 获取CPU核心数
    int cores = QThread::idealThreadCount();
    if (cores <= 0) cores = 1;
    
    // 获取CPU频率（简化版本，实际可能需要平台特定代码）
    QString frequency = "2.4GHz"; // 默认值，实际应该从系统获取
    
    // 行业精简表达：核心数@频率
    return QString("%1C@%2").arg(cores).arg(frequency);
}

QString StatusBarManager::getMemoryInfo() const
{
    // 获取系统内存信息
    qint64 totalMemoryBytes = 0;
    
#ifdef Q_OS_MACOS
    // macOS系统内存检测
    int mib[2] = {CTL_HW, HW_MEMSIZE};
    size_t length = sizeof(totalMemoryBytes);
    if (sysctl(mib, 2, &totalMemoryBytes, &length, NULL, 0) != 0) {
        totalMemoryBytes = 8LL * 1024 * 1024 * 1024; // 默认8GB
    }
#elif defined(Q_OS_WIN)
    // Windows系统内存检测
    MEMORYSTATUSEX memStatus;
    memStatus.dwLength = sizeof(memStatus);
    if (GlobalMemoryStatusEx(&memStatus)) {
        totalMemoryBytes = memStatus.ullTotalPhys;
    } else {
        totalMemoryBytes = 8LL * 1024 * 1024 * 1024; // 默认8GB
    }
#elif defined(Q_OS_LINUX)
    // Linux系统内存检测
    QFile file("/proc/meminfo");
    if (file.open(QIODevice::ReadOnly)) {
        QTextStream stream(&file);
        QString line = stream.readLine();
        while (!line.isNull()) {
            if (line.startsWith("MemTotal:")) {
                QStringList parts = line.split(QRegularExpression("\\s+"));
                if (parts.size() >= 2) {
                    totalMemoryBytes = parts[1].toLongLong() * 1024; // KB to bytes
                    break;
                }
            }
            line = stream.readLine();
        }
        file.close();
    }
    if (totalMemoryBytes == 0) {
        totalMemoryBytes = 8LL * 1024 * 1024 * 1024; // 默认8GB
    }
#else
    totalMemoryBytes = 8LL * 1024 * 1024 * 1024; // 默认8GB
#endif
    
    // 转换为GB
    int totalMemoryGB = static_cast<int>(totalMemoryBytes / (1024 * 1024 * 1024));
    
    // 行业精简表达：内存容量GB
    return QString("%1GB").arg(totalMemoryGB);
}

void StatusBarManager::forwardExportCompletedToast(const QString& message)
{
    emit exportCompletedToast(message);
}

void StatusBarManager::forwardExportFailedToast(const QString& message)
{
    emit exportFailedToast(message);
}

void StatusBarManager::onFolderIconClicked()
{
    // 使用PathManager获取标准PDF导出目录
    QString exportDir = PathManager::getPdfExportDirectory();
    
    // 确保目录存在
    QDir dir(exportDir);
    if (!dir.exists()) {
        if (!dir.mkpath(".")) {
            emit folderOpenToast("无法创建导出文件夹");
            return;
        }
    }
    
    // 打开文件夹
    bool success = QDesktopServices::openUrl(QUrl::fromLocalFile(exportDir));
    if (!success) {
        emit folderOpenToast("无法打开导出文件夹");
        return;
    }
    
    // 如果有最后导出的文件，尝试高亮选中
    if (!m_lastExportPath.isEmpty() && QFile::exists(m_lastExportPath)) {
        // 在Windows上使用explorer /select命令高亮选中文件
        #ifdef Q_OS_WIN
        QString command = QString("explorer /select,\"%1\"").arg(m_lastExportPath);
        QProcess::startDetached(command);
        #endif
        // 在其他系统上，文件夹已经打开，用户需要手动查找文件
    }
}

void StatusBarManager::onFolderBlinkTimeout()
{
    m_folderBlinkCount++;
    
    // 心跳频率闪烁3次：每次心跳包含"亮起"和"恢复"两个状态
    // 所以需要6次状态变化来完成3次完整的闪烁
    if (m_folderBlinkCount <= 6) {
        // 闪烁效果：改变背景色
        if (m_folderBlinkCount % 2 == 1) {
            // 亮起
            m_folderIconButton->setStyleSheet(
                "QPushButton { "
                "    border: none; "
                "    background-color: rgba(0, 122, 255, 0.3); "
                "    border-radius: 2px; "
                "    padding: 2px; "
                "} "
                "QPushButton:hover { "
                "    background-color: rgba(0, 122, 255, 0.4); "
                "} "
                "QPushButton:pressed { "
                "    background-color: rgba(0, 122, 255, 0.5); "
                "}"
            );
        } else {
            // 恢复
            m_folderIconButton->setStyleSheet(
                "QPushButton { "
                "    border: none; "
                "    background: transparent; "
                "    border-radius: 2px; "
                "    padding: 2px; "
                "} "
                "QPushButton:hover { "
                "    background-color: rgba(0, 122, 255, 0.1); "
                "} "
                "QPushButton:pressed { "
                "    background-color: rgba(0, 122, 255, 0.2); "
                "}"
            );
        }
    } else {
        // 闪烁完成，停止定时器
        m_folderBlinkTimer->stop();
        m_folderBlinkCount = 0;


        // 🔧 修复：闪烁完成后，关闭进度条并恢复系统信息标签
        if (m_exportProgressBar) {
            m_exportProgressBar->setVisible(false);
        }


    }
}

QIcon StatusBarManager::createFolderIcon() const
{
    QPixmap pixmap(16, 16);
    pixmap.fill(Qt::transparent);
    
    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing);
    
    // 绘制文件夹图标
    QRect folderRect(2, 4, 12, 10);
    
    // 文件夹主体
    painter.setBrush(QBrush(QColor(74, 144, 226))); // Apple Silicon蓝
    painter.setPen(QPen(QColor(50, 100, 150), 1));
    painter.drawRoundedRect(folderRect, 2, 2);
    
    // 文件夹顶部标签
    QRect tabRect(2, 2, 6, 4);
    painter.setBrush(QBrush(QColor(74, 144, 226)));
    painter.setPen(QPen(QColor(50, 100, 150), 1));
    painter.drawRoundedRect(tabRect, 1, 1);
    
    // 文件夹内部线条
    painter.setPen(QPen(QColor(255, 255, 255), 1));
    painter.drawLine(folderRect.left() + 3, folderRect.center().y(),
                    folderRect.right() - 3, folderRect.center().y());
    painter.drawLine(folderRect.left() + 3, folderRect.center().y() + 2,
                    folderRect.right() - 3, folderRect.center().y() + 2);

    return QIcon(pixmap);
}

QIcon StatusBarManager::createUpdateIcon() const
{
    QPixmap pixmap(16, 16);
    pixmap.fill(Qt::transparent);

    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制软件更新图标 - 圆形背景 + 向下箭头
    QPoint center(8, 8);
    int radius = 6;

    // 圆形背景
    painter.setBrush(QBrush(QColor(0, 122, 255))); // Apple Blue
    painter.setPen(QPen(QColor(0, 100, 200), 1));
    painter.drawEllipse(center, radius, radius);

    // 向下箭头
    painter.setPen(QPen(QColor(255, 255, 255), 2));
    painter.setBrush(Qt::NoBrush);

    // 箭头主线
    QPoint arrowStart(center.x(), center.y() - 3);
    QPoint arrowEnd(center.x(), center.y() + 3);
    painter.drawLine(arrowStart, arrowEnd);

    // 箭头两个分支
    QPoint branchLeft(arrowEnd.x() - 2, arrowEnd.y() - 1);
    QPoint branchRight(arrowEnd.x() + 2, arrowEnd.y() - 1);
    painter.drawLine(branchLeft, arrowEnd);
    painter.drawLine(branchRight, arrowEnd);

    return QIcon(pixmap);
}

void StatusBarManager::onUpdateIconButtonClicked()
{
    // 触发更新请求信号
    emit updateRequested();
}

void StatusBarManager::syncFileProcessingState()
{
    if (!m_mainWindow) {
        // 停止定时器，避免无限调用
        m_fileProcessingSyncTimer->stop();
        return;
    }

    // 获取MainWindow的文件处理状态
    bool isProcessing = m_mainWindow->isFileProcessing();

    // 添加调试日志
    static bool lastProcessingState = false;
    static int callCount = 0;
    callCount++;


    if (isProcessing != lastProcessingState) {
        lastProcessingState = isProcessing;
    }

    // 🔧 智能定时器控制：只有在文件处理中时才继续运行定时器
    if (!isProcessing) {
        // 没有文件处理活动时，停止定时器避免无限循环
        m_fileProcessingSyncTimer->stop();
    } else {
    }

    // Martin Fowler重构：移除setFileProcessing调用（由CustomFileBrowser处理）
}

void StatusBarManager::startFileProcessingSync()
{
    // 启动文件处理状态同步定时器
    if (!m_fileProcessingSyncTimer->isActive()) {
        m_fileProcessingSyncTimer->start();
    }
}

void StatusBarManager::updateVersionInfo(const QString& currentVersion, const QString& serverVersion)
{
    QString versionText;

    if (serverVersion.isEmpty() || serverVersion == "检查中...") {
        // 检查中或无服务器信息，显示当前版本（灰色）
        versionText = LimeReader::AppVersion::getVersionWithPrefix();
        m_versionLabel->setStyleSheet(
            "QLabel { "
            "    color: #8E8E93; "  // 平时灰色
            "    font-size: 12px; "
            "    font-weight: 500; "
            "    padding: 2px 6px; "
            "    background-color: rgba(142, 142, 147, 0.1); "
            "    border-radius: 4px; "
            "}"
        );
        m_updateIconButton->setVisible(false);  // 隐藏更新图标
    } else {
        // 比较版本
        VersionManager::Version current = VersionManager::Version::fromString(currentVersion);
        VersionManager::Version server = VersionManager::Version::fromString(serverVersion);

        if (server.isNewerThan(current)) {
            // 有更新时显示 v当前版本->v服务器版本（淡黄色）
            versionText = QString("v%1→v%2").arg(currentVersion, serverVersion);
            m_versionLabel->setStyleSheet(
                "QLabel { "
                "    color: #FF9F0A; "  // 淡黄色
                "    font-size: 12px; "
                "    font-weight: 500; "
                "    padding: 2px 6px; "
                "    background-color: rgba(255, 159, 10, 0.1); "
                "    border-radius: 4px; "
                "}"
            );
            m_updateIconButton->setVisible(true);  // 显示更新图标
        } else {
            // 已是最新版本，显示当前版本（灰色）
            versionText = QString("v%1").arg(currentVersion);
            m_versionLabel->setStyleSheet(
                "QLabel { "
                "    color: #8E8E93; "  // 平时灰色
                "    font-size: 12px; "
                "    font-weight: 500; "
                "    padding: 2px 6px; "
                "    background-color: rgba(142, 142, 147, 0.1); "
                "    border-radius: 4px; "
                "}"
            );
            m_updateIconButton->setVisible(false);  // 隐藏更新图标
        }
    }

    m_versionLabel->setText(versionText);
    m_versionLabel->setToolTip(QString("当前版本: %1\n服务器版本: %2").arg(currentVersion, serverVersion));
    m_updateIconButton->setToolTip("点击下载最新版本");
}

QIcon StatusBarManager::createStatusIndicatorIcon(bool isActive) const
{
    QPixmap pixmap(16, 16);
    pixmap.fill(Qt::transparent);

    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制圆形水晶按钮
    QPoint center(8, 8);
    int radius = 6;

    // 绘制水晶光泽效果（多层渐变）
    QRadialGradient gradient(center, radius);
    if (isActive) {
        // 黄色水晶（登录状态有效）
        gradient.setColorAt(0, QColor(255, 235, 59));  // 亮黄色中心
        gradient.setColorAt(0.3, QColor(255, 214, 10)); // 鲜黄色
        gradient.setColorAt(0.7, QColor(255, 193, 7));  // 黄色主体
        gradient.setColorAt(1, QColor(219, 167, 3));    // 深黄色边缘
    } else {
        // 灰色水晶（登录状态失效）
        gradient.setColorAt(0, QColor(200, 200, 200));  // 亮灰色中心
        gradient.setColorAt(0.3, QColor(170, 170, 170)); // 中灰色
        gradient.setColorAt(0.7, QColor(142, 142, 142)); // 灰色主体
        gradient.setColorAt(1, QColor(115, 115, 115));  // 深灰色边缘
    }

    painter.setBrush(QBrush(gradient));
    painter.setPen(QPen(QColor(0, 0, 0, 50), 1)); // 半透明黑色边框
    painter.drawEllipse(center, radius, radius);

    // 添加高光效果（右上角）
    QPoint highlightCenter(10, 6);
    int highlightRadius = 3;
    QRadialGradient highlightGradient(highlightCenter, highlightRadius);
    if (isActive) {
        highlightGradient.setColorAt(0, QColor(255, 255, 255, 180)); // 白色高光
        highlightGradient.setColorAt(1, QColor(255, 255, 255, 0));   // 透明边缘
    } else {
        highlightGradient.setColorAt(0, QColor(255, 255, 255, 120)); // 较弱的白色高光
        highlightGradient.setColorAt(1, QColor(255, 255, 255, 0));   // 透明边缘
    }

    painter.setBrush(QBrush(highlightGradient));
    painter.setPen(Qt::NoPen);
    painter.drawEllipse(highlightCenter, highlightRadius, highlightRadius);

    return QIcon(pixmap);
}

void StatusBarManager::updateLoginStatus(bool isActive)
{
    m_isLoginStatusActive = isActive;

    if (m_statusIndicatorButton) {
        // 更新图标
        m_statusIndicatorButton->setIcon(createStatusIndicatorIcon(isActive));

        // 更新工具提示
        if (isActive) {
            m_statusIndicatorButton->setToolTip("登录状态：已登录");
        } else {
            m_statusIndicatorButton->setToolTip("登录状态：未登录或已失效");
        }

    }
}